package com.yanggeng.demo.beginnerguidedemo.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View

class BatteryProgressBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {

    private var mPaint = Paint()
    private var mBgColor: Int = Color.WHITE
    private var mProgressColor: Int = Color.GREEN
    private var mProgress: Float = 0.7f
    private var mSingleProgressHeight = 50f
    private var mProgressWidth = 100f
    private var mProgressCount = 10
    private var mDividerSize = 30f
    private var mHeight = 0f

    init {
        mPaint.style = Paint.Style.FILL
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mHeight = mSingleProgressHeight * mProgressCount + mDividerSize * (mProgressCount - 1)
        setMeasuredDimension(mProgressWidth.toInt(), mHeight.toInt())
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val progressCount = Math.rint((mProgressCount * mProgress).toDouble())
        canvas?.let {
            it.translate(0f, mHeight)
            for (i in 0..mProgressCount) {
                val top = -(mSingleProgressHeight * (i + 1) + mDividerSize * i)
                val bottom = -(mSingleProgressHeight + mDividerSize) * i
                if (i < progressCount) {
                    mPaint.color = mProgressColor
                } else {
                    mPaint.color = mBgColor
                }
                it.drawRoundRect(0f, top, mProgressWidth, bottom, 10f, 10f, mPaint)

            }
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {

                    mProgress = 1 - it.y / mHeight
                    invalidate()
                }
                MotionEvent.ACTION_MOVE -> {
                    mProgress = 1 - it.y / mHeight
                    invalidate()
                }
            }

        }
        return true
    }

    fun startAnimation() {
        val valueAnimator = ValueAnimator.ofFloat(0f, mProgress)
        valueAnimator.duration = 500
        valueAnimator.addUpdateListener { animation ->
            run {
                mProgress = animation?.animatedValue as Float
                Log.e("Battery", "current progress: $mProgress")
                postInvalidate()
            }
        }
        valueAnimator.start()
    }
}